package rabbit.worker;

import com.rabbitmq.client.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import rabbit.common.ConsumerHandler;
import rabbit.common.rabbitMqHelper;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by root on 17-4-4.
 */
@Component
public class worker {
    private static Logger LOGGER = Logger.getLogger(worker.class.getTypeName());

    //@Autowired
    private rabbitMqHelper _rabbitMqHelper;
    private ConsumerHandler handler;

    private String consumerName;

    public worker(){ }
    public worker(rabbitMqHelper rabbitMqHelper){
        this._rabbitMqHelper=rabbitMqHelper;
    }

    public Channel getChannel() throws IOException, TimeoutException {
        return this._rabbitMqHelper.createChannel();
    }

    public void setConsumer(ConsumerHandler consumer){
        this.handler=consumer;
    }




    public void consumeMessage(){
        try{
            Channel channel = _rabbitMqHelper.createChannel();
            _rabbitMqHelper.queueDeclare(channel,true,false,false);
            Consumer consumer = new DefaultConsumer(channel){
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body){
                        if(handler==null){
                            String message = new String(body);
                            LOGGER.info(consumerName+" : "+message);
                        }
                        else{
                            handler.messageHandler(consumerTag,envelope,properties,body);
                        }
                    }
                };
            LOGGER.info("Consuming started....");
            LOGGER.info("Click on Ctrl+C to stop the process");
            while(true){
                _rabbitMqHelper.basicConsumeMessage(channel,consumer);
            }

        }catch (Exception exception){
            LOGGER.error(exception);
        }
    }


}
